#!/bin/dash

#Copyright (c) 2014 Luigi Tarenga <luigi.tarenga@gmail.com>
#Distributed under the terms of a MIT license.

#install-snapshot:
#the parameters are a little different that from the official implementation.
#actually we only need the first 2, the return value is the same as in the docs.
#input  term leader_id
#        $1   $2
#output term

if [ -d temp/master_lockdir ] ; then
   read current_term    < state/current_term
   if [ "$1" -ge "$current_term" ] ; then
      current_term=$1
      echo follower > temp/server_role
      echo "$1" > state/current_term
      echo "$2" > temp/current_leader
      cp conf/election_timeout temp/election_timeout

      # create new snapshot directory
      rm -rf state-machine-snapshot/cur
      rm -rf state-machine-data state-machine-log
      mkdir -p state-machine-log
      pax -r
      cp state-machine-snapshot/cur/cluster_nodes* conf/
      cp -r state-machine-snapshot/cur/state-machine-data .
      cp state-machine-snapshot/cur/last_included_index temp/last_log_applied
      cp state-machine-snapshot/cur/last_included_index temp/commit_index
      cp state-machine-snapshot/cur/last_included_index state/last_log_index
   fi
   #return term to update leader
   echo $current_term
else
   #no process running here, return term 0 as error
   echo 0
fi
